package com.itheima.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class SoulInterceptor implements HandlerInterceptor {


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");

        if (StrUtil.isNotBlank(token)) {


            String admin = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN + token);

            if (StrUtil.isNotBlank(admin)) {

                Admin parseObject = JSON.parseObject(admin, Admin.class);

                if (parseObject!=null) {
                    SoulHolder.set(parseObject);

                    stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN+token,admin, Duration.ofHours(1));
                    return true;
                }

            }
        }


        response.sendError(401);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
